<template>
  <div class="bg-light">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link to="/politics/real" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto">政治真题</h5>
      <span class="year-text">{{ selectedYear }}年</span>
    </div>

    <!-- 题目内容 -->
    <div class="question-container">
      <div class="question-number">第{{ currentQuestionIndex }}题 / 共{{ totalQuestions }}题</div>
      <div class="chapter-info">
        <i class="bi bi-bookmark-fill"></i>
        {{ currentQuestion.chapter }}
      </div>
      <div class="question-text" v-if="currentQuestion.checkType === 3">
        {{ currentQuestion.article }}
      </div>
      <!-- 单选题和多选题选项 -->
      <div class="question-text" v-if="currentQuestion.checkType === 1">
        {{ currentQuestion.qtitle }}(单选题)
      </div>
      <div class="question-text" v-if="currentQuestion.checkType === 2 ">
        {{ currentQuestion.qtitle }}（多选题）
      </div>
      <div class="options-container" v-if="currentQuestion.checkType === 2 || currentQuestion.checkType === 1">
        <div
            v-for="option in currentQuestion.item"
            :key="option.prefix"
            v-if="currentQuestion.checkType === 1"
            class="option-item"
            :class="{ selected: selectedOption === option.prefix }"
            @click="selectOption(option.prefix)"
        >
          {{ option.prefix }}. {{ option.content }}
        </div>
        <div
            v-for="option in currentQuestion.item"
            :key="option.prefix"
            v-if="currentQuestion.checkType === 2"
            class="option-item"
            :class="{ selected: selectedOptions.includes(option.prefix) }"
            @click="selectMultipleOption(option.prefix)"
        >
          {{ option.prefix }}. {{ option.content }}
        </div>
      </div>
    </div>

    <!-- 分析题 -->
    <div class="question-text" v-if="currentQuestion.checkType === 3">
      <div class="question-text"
           v-for="(option, index) in currentQuestion.childInfo"
           :key="index">
        {{ option.qtitle }}
        <div class="question-text">
          <textarea
              type="text"
              placeholder="请输入答案"
              class="options-container"
              @blur="handleTextareaBlur(index)"
              :key="'answerTextarea_' + index"
              v-model="userInputAnswer[index]"
          />
        </div>

      </div>
    </div>

    <!-- 导航按钮 -->
    <div class="navigation-buttons d-flex justify-content-between">
      <div class="d-flex gap-2">
        <button
            class="btn btn-outline-secondary"
            @click="prevQuestion"
            :disabled="currentQuestionIndex === 1"
        >
          上一题
        </button>
        <button
            class="btn btn-outline-secondary"
            @click="nextQuestion"
            :disabled="currentQuestionIndex === totalQuestions"
        >
          下一题
        </button>
        <button
            class="btn btn-primary submit-button"
            @click="submitAnswers(1)"
            :class="{ 'disabled-button': isSubmitted }"
            @click.prevent="disableButton"
        >
          结束答题
        </button>
      </div>
      <router-link
          @click.prevent="submitAnswers(2)"
          :to="`/politics/real/explanation?year=${selectedYear}&question=${questionId}&userAnswer=${getSelectedAnswerValue()}&examPaperId=${examPaperId}&currentQuestionIndex=${currentQuestionIndex}`"
          class="btn btn-primary"
      >
        <i class="bi bi-journal-text"></i>
        答案解析
      </router-link>
    </div>
  </div>
</template>

<script>
import http from '@/router/http';
import router from "@/router/index";
export default {
  name: 'PoliticsRealPracticeView',
  data() {
    return {
      examPaperId: null,
      selectedYear: 2024,
      currentQuestionIndex: 1,
      selectedOption: null,
      selectedOptions: [], // 用于存储多选题和复选框题选中的选项
      totalQuestions: 0,
      currentQuestion: [],
      answerContentRecords: [], // 用于存储分析题答案内容
      userInputAnswer: {}, // 存储用户在富文本输入框中输入的答案
      userInputHistory: {}, // 用于存储每道题用户输入的历史记录（包含选项选择情况和输入框内容）
      answeredQuestions: [], // 存储用户已回答的题目及答案信息
      thisTimeAnswer: {},
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      questionId: null,
      correctAnswer: null,
      currrentAnswer: null,
    }
  },
  created() {// 从路由参数获取年份等原有逻辑保持不变
    const year = parseInt(this.$route.query.year);
    if (year) {
      this.selectedYear = year;
    }
    const currentIndex = parseInt(this.$route.query.currentIndex);
    if(currentIndex){
      this.currentQuestionIndex = currentIndex;
    }
    const examPaperId = this.$route.query.examPaperId;
    this.examPaperId = examPaperId;
    const questionId = this.currentQuestion.questionId;
    if (this.userInputHistory[questionId]) {
      // 如果有历史记录，恢复相应的选项选择状态和输入框内容，原逻辑保持不变
      if (this.currentQuestion.checkType === 1) {
        this.selectedOption = this.userInputHistory[questionId].selectedOption;
      } else if (this.currentQuestion.checkType === 2) {
        this.selectedOptions = this.userInputHistory[questionId].selectedOptions;
      } else if (this.currentQuestion.checkType === 3) {
        this.userInputAnswer = this.userInputHistory[questionId].userInputAnswer;
      }
    }
    // 调用获取数据的方法，从后端接口获取题目数据
    this.fetchQuestionData().then(() => {
      if(this.answerContentRecords && this.answerContentRecords.length > 0) {
        const questionId = this.currentQuestion.questionId;
        this.restoreQuestionStateFromHistory(questionId);
      }
    });
    this.startTime = Date.now();


  },
  methods: {
    async fetchQuestionData() {
      try {
        const response = await http.get(`/student/question/getQuestionPoliticsInfo?examPaperId=${this.examPaperId}&currentQuestionIndex=${this.currentQuestionIndex}`);
        if (response.status === 200 && response.data && response.data.response) {
          this.totalQuestions = response.data.response.totalQuestions;
          this.currentQuestion = response.data.response;
          this.questionId = response.data.response.questionId;
          this.correctAnswer = response.data.response.correctAnswer;
          if (response.data.response.childInfo && response.data.response.childInfo.length > 0) {
            if (response.data.response.childInfo.length === 1) {
              this.currentQuestion.item = response.data.response.childInfo[0].item;
              this.currentQuestion.qtitle = response.data.response.childInfo[0].qtitle;
            } else if (response.data.response.childInfo.length > 1) {
              this.currentQuestion.childInfo = response.data.response.childInfo;
            }
            if(response.data.response.answerContentRecords && response.data.response.answerContentRecords.length > 0){
              if(this.answerContentRecords === null || this.answerContentRecords.length === 0){
                response.data.response.answerContentRecords.forEach(record => {
                  this.answerContentRecords.push({
                    questionId: record.questionId,
                    content: record.content
                  });
                });
              }
            }
          }
        }
      } catch (error) {
        console.error('获取题目数据失败:', error);
      }
    },
    selectOption(key) {
      this.selectedOption = key;
      this.currrentAnswer = this.selectedOption;
      this.thisTimeAnswer[this.currentQuestion.questionId] = {
        questionId: this.currentQuestion.questionId,
        userAnswer: this.selectedOption
      };
      // 记录单选题选项选择情况到历史记录
      this.recordOptionSelection();
    },
    selectMultipleOption(key) {
      const index = this.selectedOptions.indexOf(key);
      if (index > -1) {
        this.selectedOptions.splice(index, 1);
      } else {
        this.selectedOptions.push(key);
      }
      this.currrentAnswer = this.selectedOptions.join(',');

      this.thisTimeAnswer[this.currentQuestion.questionId] = {
        questionId: this.currentQuestion.questionId,
        userAnswer: [...this.selectedOptions]
      };
      // 记录多选题选项选择情况到历史记录
      this.recordOptionSelection();
    },
    handleTextareaBlur(index) {
      let answer = null;
      answer = Object.values(this.userInputAnswer);
      const questionId = this.currentQuestion.questionId;
      if (answer && answer.length > 0) {
        this.thisTimeAnswer[questionId] = {
          questionId: this.currentQuestion.questionId,
          userAnswer: this.userInputAnswer
        };
        this.userInputHistory[questionId] = {
          selectedOption: this.currentQuestion.checkType === 1 ? this.selectedOption : null,
          selectedOptions: this.currentQuestion.checkType === 2 ? [...this.selectedOptions] : [],
          userInputAnswer: this.userInputAnswer
        };
      }
    },
    recordOptionSelection() {
      const questionId = this.currentQuestion.questionId;
      const questionHistory = {
        selectedOption: this.currentQuestion.checkType === 1? this.selectedOption : null,
        selectedOptions: this.currentQuestion.checkType === 2? [...this.selectedOptions] : [],
        userInputAnswer: this.currentQuestion.checkType === 3? this.userInputAnswer : {}
      };
      this.userInputHistory[questionId] = questionHistory;
    },
    restoreQuestionStateFromHistory(questionId) {
      if (this.userInputHistory[questionId]) {
        // 如果userInputHistory中有记录，恢复相应的选项选择状态和输入框内容
        if (this.currentQuestion.checkType === 1) {
          this.selectedOption = this.userInputHistory[questionId].selectedOption;
        } else if (this.currentQuestion.checkType === 2) {
          this.selectedOptions = this.userInputHistory[questionId].selectedOptions;
        } else if (this.currentQuestion.checkType === 3) {
          this.userInputAnswer = this.userInputHistory[questionId].userInputAnswer;
        }
      } else {
        // 如果userInputHistory中无记录，再尝试从answerContentRecords恢复（如果有数据的话）
        if (this.answerContentRecords && this.answerContentRecords.length > 0) {
          const answerRecord = this.answerContentRecords.find(record => record.questionId === questionId);
          if (answerRecord && this.currentQuestion.checkType === 1) {
            this.selectedOption = answerRecord.content[0];
          } else if (answerRecord && this.currentQuestion.checkType === 2) {
            const selectedOptionsArray = answerRecord.content;
            this.selectedOptions = selectedOptionsArray;
          } else if (answerRecord && this.currentQuestion.checkType === 3) {
            const selectedOptionsArray = answerRecord.content;
            this.userInputAnswer = selectedOptionsArray;
          }else {
            // 如果都没有记录，设置为默认初始状态
            if (this.currentQuestion.checkType === 1) {
              this.selectedOption = null;
            } else if (this.currentQuestion.checkType === 2) {
              this.selectedOptions = [];
            } else if (this.currentQuestion.checkType === 3) {
              this.userInputAnswer = {};
            }
          }
        } else {
          // 如果都没有记录，设置为默认初始状态
          if (this.currentQuestion.checkType === 1) {
            this.selectedOption = null;
          } else if (this.currentQuestion.checkType === 2) {
            this.selectedOptions = [];
          } else if (this.currentQuestion.checkType === 3) {
            this.userInputAnswer = {};
          }
        }
      }
    },
    getSelectedAnswerValue() {
      let answerValue = null;
      if (this.currentQuestion.checkType === 1) {
        // 单选题，直接返回选中的选项值
        answerValue = this.selectedOption;
      } else if (this.currentQuestion.checkType === 2) {
        // 多选题，将选中的选项值用逗号拼接成字符串
        answerValue = this.selectedOptions.join(',');
      }
      return answerValue;
    },
    prevQuestion() {
      if (this.currentQuestionIndex > 1) {
        // const currentTime = Date.now(); // 获取当前时间（毫秒数）
        // this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        this.currentQuestionIndex--;
        this.fetchQuestionData().then(() => {
          const questionId = this.currentQuestion.questionId;
          this.restoreQuestionStateFromHistory(questionId);
        });

        let answer = null;
        if (this.currentQuestion.checkType === 1) {
          answer = this.selectedOption;
        } else if (this.currentQuestion.checkType === 2) {
          if (this.selectedOptions.length > 0) {
            answer = [...this.selectedOptions];
          }
        } else if (this.currentQuestion.checkType === 3) {
          answer = Object.values(this.userInputAnswer);
        }

        // 判断答案不为空时才进行后续操作
        if (answer && answer.length > 0) {
          const questionAnswerInfo = {
            questionId: this.currentQuestion.questionId,
            answer: answer
          };
          const existingIndex = this.answeredQuestions.findIndex(item => item.questionId === questionAnswerInfo.questionId);
          if (existingIndex > -1) {
            // 如果已存在相同questionId的答案，覆盖掉之前的答案
            this.answeredQuestions[existingIndex] = questionAnswerInfo;
          } else {
            // 如果不存在，则添加新的答案信息
            this.answeredQuestions.push(questionAnswerInfo);
          }
        }

        if (this.currentQuestion.checkType === 1) {
          this.selectedOption = null;
        } else {
          this.selectedOptions = [];
        }

      }
    },
    nextQuestion() {
      if (this.currentQuestionIndex < this.totalQuestions) {
        // const currentTime = Date.now(); // 获取当前时间（毫秒数）
        // this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        this.currentQuestionIndex++;

        // 先调用获取题目数据的方法，在成功获取后再处理后续逻辑
        this.fetchQuestionData().then(() => {
          const questionId = this.currentQuestion.questionId;
          this.restoreQuestionStateFromHistory(questionId);
        });

        let answer = null;
        if (this.currentQuestion.checkType === 1) {
          answer = this.selectedOption;
        } else if (this.currentQuestion.checkType === 2) {
          if (this.selectedOptions.length > 0) {
            answer = [...this.selectedOptions];
          }
        } else if (this.currentQuestion.checkType === 3) {
          answer = Object.values(this.userInputAnswer);
        }

        // 判断答案不为空时才进行后续操作
        if (answer && answer.length > 0) {
          const questionAnswerInfo = {
            questionId: this.currentQuestion.questionId,
            answer: answer
          };
          const existingIndex = this.answeredQuestions.findIndex(item => item.questionId === questionAnswerInfo.questionId);
          if (existingIndex > -1) {
            // 如果已存在相同questionId的答案，覆盖掉之前的答案
            this.answeredQuestions[existingIndex] = questionAnswerInfo;
          } else {
            // 如果不存在，则添加新的答案信息
            this.answeredQuestions.push(questionAnswerInfo);
          }
        }

        if (this.currentQuestion.checkType === 1) {
          this.selectedOption = null;
        } else {
          this.selectedOptions = [];
        }

      }
    },
    async submitAnswers(type) {
      const submitButton = document.querySelector('button.btn.btn-primary.submit-button');
      if (submitButton) {
        submitButton.disabled = true; // 直接设置按钮的disabled属性为true，使其置灰不可点击
      }
      const currentTime = Date.now(); // 获取当前时间（毫秒数）
      this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
      try {
        const submitData = [];
        this.answeredQuestions.forEach(question => {
          const {questionId, answer} = question;
          submitData.push({
            questionId: questionId,
            userAnswer: answer
          });
        });
        let answer = null;
        if (this.currentQuestion.checkType === 1) {
          answer = this.selectedOption;
        } else if (this.currentQuestion.checkType === 2) {
          if (this.selectedOptions.length > 0) {
            answer = [...this.selectedOptions];
          }
        } else if (this.currentQuestion.checkType === 3) {
          answer = Object.values(this.userInputAnswer);
        }
        // 判断答案不为空时才添加到提交数据中
        if (answer && answer.length > 0) {
          const questionAnswerInfo = {
            questionId: this.currentQuestion.questionId,
            userAnswer: answer
          };
          const existingIndex = submitData.findIndex(item => item.questionId === questionAnswerInfo.questionId);
          if (existingIndex > -1) {
            // 如果已存在相同questionId的答案，覆盖掉之前的答案
            submitData[existingIndex] = questionAnswerInfo;
          } else {
            // 如果不存在，则添加新的答案信息
            submitData.push(questionAnswerInfo);
          }
        }
        this.answerContentRecords.forEach(record => {
          const {questionId, content} = record;
          const existingIndex = submitData.findIndex(item => item.questionId === questionId);
          if (existingIndex === -1) {
            submitData.push({questionId, userAnswer: content});
          }
        });

        const thisTimeAnswerArray = Object.values(this.thisTimeAnswer);
        const submitInfo = {
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1, // 资源类型为1，表示政治历史真题
          thisTimeData: thisTimeAnswerArray,
          childDtos: submitData
        };
        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForPolitics', submitInfo);
        if (response.status === 200) {
          console.log('答题数据提交成功');
          if(type === 1){
            router.push('/politics/real');
          }
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          if(type === 1){
            router.push('/politics/real');
          }
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    },
  }
}
</script>

<style scoped>
body {
  background-color: #f0f9f9;
  padding-bottom: 70px;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header.dropdown-toggle {
  padding: 4px 10px;
  font-size: 0.9rem;
}

.header.dropdown-menu {
  min-width: 100px;
}

.header.dropdown-item.active {
  background-color: #B19CD9;
  color: white;
}

.question-container {
  background: white;
  margin: 15px;
  padding: 20px;
  border-radius: 15px;
  line-height: 1.8;
}

.question-number {
  color: #666;
  margin-bottom: 10px;
  font-size: 0.9rem;
}

.chapter-info {
  color: #B19CD9;
  font-size: 0.9rem;
  margin-bottom: 15px;
}

.question-text {
  margin-bottom: 20px;
  color: #333;
}

.options-container {
  margin-top: 15px;
}

.option-item {
  background: #f8f9fa;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
}

.option-item:hover {
  background: #e9ecef;
}

.option-item.selected {
  background: #B19CD9;
  color: white;
}

.navigation-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 15px;
  background: white;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.year-text {
  font-size: 0.9rem;
  color: #666;
  padding: 4px 10px;
}

textarea {
  width: 80%;
  height: 200px;
  margin: 0 auto;
  display: block;
  resize: vertical;
}

.disabled-button {
  pointer-events: none; /* 禁用按钮的点击事件 */
  opacity: 0.5; /* 改变透明度，使其视觉上呈现置灰效果 */
  background-color: #ccc !important; /* 可根据需要调整置灰后的背景色 */
  border-color: #ccc !important; /* 调整边框颜色与背景色匹配 */
}
</style>